<template>
    <p>数据筛选</p>
    <el-form :inline="true" :model="data" class="demo-form-inline">
        <el-form-item label="产品编号:">
            <el-input v-model="data.Product_Number" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="产品名称:">
            <el-input v-model="data.Product_Name" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="仓库:">
            <el-select v-model="data.Warehouse_ID" placeholder="请选择" clearable style="width: 100px;">

                <el-option v-for="item in stroageData" :label="item.warehouse_Name" :value="item.id" />
            </el-select>
        </el-form-item>

        <el-form-item label="批次:">
            <el-input v-model="data.Batch" placeholder="" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="GetInventory">查询</el-button>
        </el-form-item>
    </el-form>

    <div class="header-container">
        <span>数据列表</span>
        <el-button type="primary" @click="handleExport">导出</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="createTime" label="日期" width="180">
            <template v-slot="scoped">
                {{ moment(scoped.row.createTime).format("yyyy-MM-DD") }}
            </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="180" />
        <el-table-column prop="product_Number" label="产品编号" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="产品规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="unit_Name" label="存储单位" />
        <el-table-column prop="warehouse_Name" label="仓库" />
        <el-table-column prop="beging" label="期初" />
        <el-table-column prop="intTo" label="入库" />
        <el-table-column prop="outTo" label="出库" />
        <el-table-column label="期末">
            <template v-slot="scoped">
                {{ scoped.row.beging + scoped.row.intTo - scoped.row.outTo }}
            </template>
        </el-table-column>

    </el-table>

    <div class="demo-pagination-block">
        <el-pagination v-model:current-page="data.PageIndex" v-model:page-size="data.PageSize"
            :page-sizes="[1, 20, 25, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="data.Count" next-text="下一页" prev-text="上一页" />
    </div>

</template>

<script lang="ts" setup>
import { statementRed } from '@/http/axiosHelper'
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import moment from 'moment'
const tableData = ref([])

const data = ref({
    PageIndex: 1,
    PageSize: 2,
    Count: 0,
    Product_Number: '',
    Product_Name: '',
    Warehouse_ID: "",
    Batch: ''
})

const GetInventory = () => {
    statementRed.get("api/Inventory/GetBeginnEnd", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
            Product_Number: data.value.Product_Number,
            Product_Name: data.value.Product_Name,
            Warehouse_ID: data.value.Warehouse_ID,
            Batch: data.value.Batch,
        }
    })
        .then(res => {
            tableData.value = res.data.data;
            data.value.Count = res.data.totalCount
        })
        .catch(err => {
            ElMessage.error("查询失败", err)
        })
}

const stroageData = ref([{
    warehouse_Name: '',
    id: ''
}])
const GetSrotage = () => {
    statementRed.get("api/Inventory/GetWarehouse")
        .then(res => {
            stroageData.value = res.data.data;
        })
}




// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await statementRed({
            url: 'api/Inventory/GetBeginnEndExport', // 后端接口地址
            method: 'GET',
            params: {
                PageIndex: data.value.PageIndex,
                PageSize: data.value.PageSize,
                Product_Number: data.value.Product_Number,
                Product_Name: data.value.Product_Name,
                Warehouse_ID: data.value.Warehouse_ID,
                Batch: data.value.Batch,
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    // 后端返回的 Content-Disposition 格式：attachment; filename="期初期末_20250725101010.xlsx"
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '期初期末数据.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '期初期末数据.xlsx';
}

watch(() => { data.value.PageIndex, data.value.PageSize }, () => {
    GetInventory();
}, { deep: true })


onMounted(() => {
    GetInventory();
    GetSrotage();
})

</script>

<style scoped>
.header-container {
    display: flex;
    /* 启用 Flex 布局 */
    justify-content: space-between;
    /* 左右两端对齐 */
    align-items: center;
    /* 垂直居中对齐 */
    padding: 16px;
    /* 可选：添加内边距 */
    border-bottom: 1px solid #eee;
    /* 可选：添加底部边框分隔 */
}
</style>